package io.file;

import framework.AbstractTest;
import utils.Log;
import utils.StringUtils;

import java.io.RandomAccessFile;

/**
 * Created by shane on 2018/5/21.
 */
public class UsingRandomAccessFile extends AbstractTest {
    protected static final String TAG = UsingRandomAccessFile.class.getName();

    @Override
    public void test(String[] args) {
        super.test(args);

        String filename = getDefOutputFile(args);

        try {
            // RandomAccessFile 实现了 DataOutput, DataInput, 接口
            RandomAccessFile rf = new RandomAccessFile(filename, FILE_MODE_RW);
            for (int i=0; i<7; i++) {
                rf.writeDouble(i*1.414);
            }
            rf.writeUTF("The end of the file");

            display(filename);

            rf = new RandomAccessFile(filename, FILE_MODE_RW);
            rf.seek(5*8);
            rf.writeDouble(47.001);
            rf.close();
            display(filename);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String getTag() {
        return TAG;
    }

    private static void display(String filename) {
        if (StringUtils.isEmpty(filename)) {
            return;
        }

        try {
            RandomAccessFile rf = new RandomAccessFile(filename, FILE_MODE_R);
            for (int i=0; i < 7; i++) {
                Log.vn(String.valueOf(
                        StringUtils.getAppendString("Value:", String.valueOf(i), ":, ", String.valueOf(rf.readDouble()))
                ));
            }
            Log.vn(rf.readUTF());
            rf.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
